<?php
$serv = new swoole_server('0.0.0.0', 9513);
$serv->set(array(
    'daemonize' => 1,
    'worker_num' => 100, //worker进程数量
//    'task_worker_num' => 10, //task进程数量 即为维持的MySQL连接的数量
    'log_file' => '/var/www/swoole/cli/log/9513.log',
    'max_request' => 10000, // 单个worker 最大处理数
    "open_eof_check" => 1,
    "package_eof" => "\r\n\r\n",
    "dispatch_mode" => 1  // 1平均分配 2固定taskid 3 抢占
));

// worker start
function my_onWorkerStart($serv, $worker_id)
{
    $notify_log = "/var/www/swoole/cli/log/" . 'nodesyn-' . date('Y-m-d', time()) . '.txt';
    $notify_log2 = "/var/www/swoole/cli/log/" . 'syn_olddata-' . date('Y-m-d', time()) . '.txt';


    $ip = '120.31.131.231'; // redis服务器ip地址
    $port = '6379'; // redis服务器端口
    $passwd = '!@#$981596276'; // redis密码
    $redis = new Swoole\Coroutine\Redis();
    $redis->connect($ip, $port);
    $redis->auth($passwd);
    $keys = "list-data";
    $secondList = "second-data";
    $db = new Swoole\Coroutine\MySQL();
    $server = array(
        'host' => '120.31.136.107',
        'user' => 'root',
        'password' => 'd23a048282d9f0e3',
        'database' => 'pay_system_v5',
    );

    if($db->connect($server) == false ){
        $db->connect($server);
    }

    for ($i=0;$i<10000;$i++){
        $data = $redis->brPop($keys, 2);
        if ($data == false) {
            continue;
        }
        file_put_contents("/var/www/swoole/cli/log/redis1.txt",json_encode($data)."--|\r\n",FILE_APPEND);
        $data = json_decode($data[1], true);
        if($data) {
            $result = $db->query("SELECT * FROM pay_order where order_id =  '{$data['order_id']}'",5);
            if($result === false){
                $db->close();
                $db->connect($server);
                $result = $db->query("SELECT * FROM pay_order where order_id =  '{$data['order_id']}'",5);
            }

            if ($result) {
                $temp = request_post($result[0]['notify_url'], json_encode($result[0]));
                if ($temp == "SUCCESS" || $temp == "success") {
                    $rand = mt_rand(1000, 99999);
                    $db->query("update pay_order set  platform = '{$rand}' where order_id = '{$data['order_id']}'");
//                    continue;
                }
            }
        }

    }

}


function my_onReceive($serv, $fd, $from_id, $data)
{
}

function my_onTask($serv, $task_id, $from_id, $sql)
{

}

function my_onFinish($serv, $task_id, $data)
{
}


//function PostNotify($orderid, $Channel = "", $bank_money = 0,$notify_type = 1)
//{
//    //协程客户端
//    $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
//    if (!$client->connect('127.0.0.1', 9509, 1))
//    {
//        return false;
//    }
//    $client->send("SELECT *  FROM pay_order WHERE order_id='{$orderid}");
//    $orderinfo =  $client->recv();
//    $client->close();
//    var_dump($orderinfo);
//
//    if(!$orderinfo){
//        return false;
//    }
//
//
//    $notify_data = '';
//    $notify_data .= date('Y-m-d H:i:s', time());
//    $notify_data .= '|' . $orderid;
//    if ($orderinfo && $bank_money) {
//        $url = $orderinfo["notify_url"];
//        if (!empty($orderinfo["sn"])) {
//            $transactionId = $orderinfo["sn"];
//        } else {
//            $transactionId = $orderinfo["up_sn"];
//        }
//        $data = array(
//            'order_id' => $orderinfo["order_id"],
//            'orderNo' => $orderinfo["system_order_id"],
//            'money' => $bank_money,
//            'mch' => $orderinfo["mch"],
//            'pay_type' => $orderinfo["pay_type"],
//            'commodity_name' => $orderinfo["commodity_name"],
//            'extra' => $orderinfo["extra"],
//            'transactionId' => $transactionId,
//            'time' => $orderinfo["down_time"],
//            'status' => 1,
//            'sign' => md5($orderinfo["order_id"] . $orderinfo["system_order_id"] . $bank_money . $orderinfo["mch"] . $orderinfo["pay_type"] . $orderinfo["down_time"] . md5($orderinfo["mch_key"])),
//        );
//
//        $sign_str = $orderinfo["order_id"] . '--' . $orderinfo["system_order_id"] . '--' . $bank_money . $orderinfo["mch"] . '--' . $orderinfo["pay_type"] . '--' . $orderinfo["down_time"] . '--' . $orderinfo["mch_key"];
//        file_put_contents($notify_log2, $sign_str . PHP_EOL, FILE_APPEND);
//        $url = str_replace('&amp;', '&', $url);
//        $notify_data .= '|' . json_encode($data) . '|' . $url;
//        if ($notify_type == 2) {
//            $newdata = @http_build_query($data);  //把参数转换成URL数据
//            $get_url = $url . '?' . $newdata;
//            $result = @file_get_contents($get_url);
//            $notify_data .= '|get同步结果' . json_encode($result);
//        }
//        if($notify_type == 1){
//            echo 1;die;
//            $result = request_post($url, $data);
//            $notify_data .= '|同步结果' . json_encode($result);
//        }
//        $result = strtolower($result);
//        $pos = strpos($result, 'success');
//        if ($pos === false) {
//            $return_res = 'ERR2';
//        } else {
//            $return_res = "OK";
//
//            $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
//            if (!$client->connect('127.0.0.1', 9509, 1))
//            {
//                return false;
//            }
////            $client->send("update pay_order set down_time = ? where id ='{$orderid}");
////            $client->recv();
////            $client->close();
//
//
////
////            $updateSql = $swoole_mysql->prepare('update pay_order set down_time = ? where id = ?');
////            $updateSql->execute(array(time(),$orderid));
//        }
//        $notify_data .= '|res=' . $return_res;
//        file_put_contents($notify_log, $notify_data . PHP_EOL, FILE_APPEND);
//
//    } else {
//        $return_res = "orderinfo is null";
//        $notify_data .= '|res=' . $return_res;
//        file_put_contents($notify_log, $notify_data . PHP_EOL, FILE_APPEND);
//        return $return_res;
//    }
//
//}

function request_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }
    $postUrl = $url;
    $curlPost = $param;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    curl_setopt($ch, CURLOPT_TIMEOUT,35);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return $data;
}

function send_post($postUrl, $post_data = '', $isxml = false, $timeout = 8)
{
    if (empty($postUrl) || empty($post_data)) {
        return false;
    }
    $curlPost = $post_data;
    $header[] = "Content-type: text/html";
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $postUrl);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return $data;
}

$serv->on('receive', 'my_onReceive');
$serv->on('task', 'my_onTask');
$serv->on('Finish', 'my_onFinish');
$serv->on('WorkerStart', 'my_onWorkerStart');

$serv->start();//启动server
